package com.murshidm.imdboards;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Whitelist;

public class main extends Activity {
    
	final Activity activity = this;
	final static String	LOG_TAG	= "IMDBLOG"; // logging
	WebView web1; // webview
	ProgressBar loadingProgressBar; //progress bar control
    String homepage = "http://m.imdb.com"; // home
    String CurrentWebviewURL = "NULL"; // to call from menu (filter a movie url and display messageboard )
    Button btnView,btnHome; // view button
    ArrayList<String> backList = new ArrayList<String>();
//---------------------------------------------------------------------------------------------------
//   START ONCREATE METHOD
//---------------------------------------------------------------------------------------------------
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        try {
        	Log.i(LOG_TAG, " IMDBOARDS START "); 
			super.onCreate(savedInstanceState);        
			requestWindowFeature(Window.FEATURE_NO_TITLE); // hide title
			setContentView(R.layout.main);
			loadingProgressBar=(ProgressBar)findViewById(R.id.progressBar1); // get progressbar id from layout/main.xml
			web1 = (WebView) findViewById(R.id.webview1); //R.id.webview = layout/main.xml
			web1.getSettings().setJavaScriptEnabled(true); // enable js
			web1.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.872.0 Safari/535.2"); // user agent for desktop view
			btnView = (Button) findViewById(R.id.btnView); 
			btnHome = (Button) findViewById(R.id.btnHome); 
			btnView.setEnabled(false);
			btnView.setTextColor(Color.rgb(0, 0, 0));
			// load url in webview
			web1.loadUrl(homepage);
			
		    //button view
		    btnView.setOnClickListener(new View.OnClickListener() {
			      public void onClick(View v) {
			    	 Log.i(LOG_TAG, " VIEW BUTTON CLICKED "); 
			    	 openMboard(CurrentWebviewURL);
			      }
			});
		    
		    //button home
		    btnHome.setOnClickListener(new View.OnClickListener() {
			      public void onClick(View v) {
			    	  web1.loadUrl(homepage);
			      }
			});
			
			// start webview client
			web1.setWebViewClient(
				new WebViewClient() {
					
						// page start
						@Override  
						public void onPageStarted(WebView view, String url, Bitmap favicon) {
							//none	
							
						}
						
						public void onPageFinished(WebView view, String url) {
							CurrentWebviewURL = url; // save current url (for menu>message board)
							
							addBackList(url);// add url's to backList
							
							if(getMovieTitleId(url)!="null"){ // show view button if movie id available
								btnView.setEnabled(true);
								btnView.setTextColor(Color.YELLOW);


							}
							else{
								//btnView.setVisibility(View.GONE);			
								btnView.setEnabled(false);
								btnView.setTextColor(Color.rgb(0, 0, 0));

							}
							//Log.i(LOG_TAG, " FINISHED URL  "+url); 
						}
						
						// load all links within app , also can be used to find out which link was clicked
						@Override
			            public boolean shouldOverrideUrlLoading(WebView view, String url)
			            {  		
							String imdbLocation = getImdbSite(url); //get domain whether its mobile or desktop
							String threadLocation = getThreadLocation(url); // get whether main board or individual thread
							String loadJSfile = getJSfile(threadLocation); // get js file based on thread location
							
							if(imdbLocation.equals("mobile")){ // mobile load webview default
								web1.getSettings().setUserAgentString("Mozilla/5.0 (Linux; U; Android 0.5; en-us) AppleWebKit/522+ (KHTML, like Gecko) Safari/419.3"); // user agent for mobile
								view.loadUrl(url);
							}
							else if(imdbLocation.equals("desktop")){ // desktop - load webview with custom HTML
								//Log.i(LOG_TAG, " DESKTOP EXTRACT START "); 
								String myhtml = extractHTML(url,loadJSfile);
								//Log.i(LOG_TAG, " LOAD MYHTML "); 
								web1.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.872.0 Safari/535.2"); // user agent for desktop view
								view.loadDataWithBaseURL(url,myhtml, "text/html", "utf-8",url);
							}
							else if(imdbLocation.equals("secure")){ // secure links. login page etc.
								view.loadUrl(url);
							}
							else{ // external link. load default browser
								Uri uri = Uri.parse(url.toString());
					            Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);
					            startActivity(browserIntent);
								return true;
							}
						
						
							
						return false;
			            }
				} // end new webview

			 ); 
			// end webview client
			
			// webchrome client - to track progress of webview 
			web1.setWebChromeClient(new WebChromeClient() {
				
				   @Override
				   public void onProgressChanged(WebView view, int newProgress) {
			    	   super.onProgressChanged(view, newProgress);
			    	   loadingProgressBar.setProgress(newProgress);
			        	   if (newProgress == 100) {
			        		   loadingProgressBar.setVisibility(View.GONE);// hide progress bar
			        	   } 
			        	   else{
			        		   loadingProgressBar.setVisibility(View.VISIBLE); // show progress bar
			        	   }

				   }
			});
			// end webchrome client
			
		} 
        catch (Exception e) {
			e.printStackTrace();
		}
        
    }
//---------------------------------------------------------------------------------------------------
//   END ONCREATE METHOD
//---------------------------------------------------------------------------------------------------
    
 // add url's to backList
    private void addBackList(String myurl){
    	if(backList.size()>0){
			String lastItem = backList.get(backList.size()-1);
			Log.i(LOG_TAG, " lastItem "+lastItem); 
			if(!lastItem.equals(myurl))//if url is not equal to last item
			{	backList.add(myurl); // add url to backlist
				Log.i(LOG_TAG, " ADD URL "+myurl); 
			}
			
			for(int i=0;i<backList.size();i++)
					Log.i(LOG_TAG, i + "-"+backList.get(i)); 
			Log.i(LOG_TAG, " ----------------------------------------- "); 
		}
		else{
			backList.add(myurl); // add starting url
		}
    	
    	// keep only 10 items
    	if(backList.size()>10){
    		backList.remove(0); //remove first item
    	}
	}
    
    // start extract board HTML
    private String extractHTML(String myurl,String loadJS){
    	
		String html ="empty";
		  
		try 
    	{
    		Long start =  System.currentTimeMillis();
		    Log.i(LOG_TAG, "start conenct = " + (start / 1000) % 60 + ":" + start % 1000);
    		
    		Document doc = Jsoup.connect(myurl)
    				.userAgent("Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1")
    				.timeout(10000) // 10 secs
    				.get();
    		
    		Long end =  System.currentTimeMillis();
    		Log.i(LOG_TAG, " end connect  = " + (end / 1000) % 60 + ":" + end % 1000);
    		
			if(doc!=null && doc.getElementById("pagecontent")!= null){ // proceed only if pagecontent div exists
				Element content = doc.getElementById("pagecontent");
								
					if(content.html().length()>0)
					{
						String pageTitle = doc.title().toString();
						
						// table clean all unwanted tags. preserve only some tags given in addTags
						String table_clean = "<div id='MainWrapper'>" + 
												Jsoup.clean(content.html(), Whitelist.simpleText().addTags("table","tbody","tr","td","a","small","br","blockquote").addAttributes("a","href","name")) + 
											  "</div>";
							
						Long fin =  System.currentTimeMillis();
						Log.i(LOG_TAG, " fin  = " + (fin / 1000) % 60 + ":" + fin % 1000);
				        
					    html = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"+
					    	   "<html><head><title>"+pageTitle+"</title>"+
					    	   "<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js' language='javascript'></script>" +
				    		   "<script src='file:///android_asset/"+loadJS+"?16' language='javascript'></script>" +
				    		   "<link rel='stylesheet' type='text/css' href='file:///android_asset/format.css?16' />  "+
				    		   "</head><body>" + table_clean + "</body></html>";
					    
					    //System.out.println(html); 
					}
			} 
    	}    		
	    catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				//Log.i(LOG_TAG, "error - " + e.toString()); 
				html="<span style='color:red;'>Error! "+e.toString()+"</span><br><br> Refresh page <a href='"+myurl+"'>"+myurl+"</a>";
		}
    	//Log.i(LOG_TAG, " myurl "+myurl); 
    	//Log.i(LOG_TAG, " loadJS "+loadJS); 
    	return html;

    }
    // end extract board HTML
    
    // get imdbsite location
	public String getImdbSite(String myurl){
		if(myurl!=""){	
			if(myurl.startsWith("http://m.imdb.com")){
				return "mobile"; // imdb mobile
			}
			else if(myurl.startsWith("http://www.imdb.com")){
				return "desktop"; // imdb desktop
			}
			else if(myurl.startsWith("https://secure.imdb.com")){
				return "secure"; // imdb desktop
			}
			else{
				return "external"; // external link
			}
		}
		
		return "null"; // null
	}
	
	// get thread location (whether its main thread or individual post)
	// allthreads - [http:, , www.imdb.com, title, tt1600195, board, threads]
	// onethread - [http:, , www.imdb.com, title, tt1600195, board, thread, 189055561]
	public String getThreadLocation(String myurl){
		if(myurl!=""){	
			if(myurl.startsWith("http://www.imdb.com")){
				List<String> urlitems = Arrays.asList(myurl.split("/"));	// split url by /

				if(urlitems.size()>6 && urlitems.get(5).equals("board") && urlitems.get(6).equals("threads")){ //mainboard
					return "allthreads";
				}
				else if(urlitems.size()>7 && urlitems.get(5).equals("board") && urlitems.get(6).equals("thread")){ // invidual thread
					return "onethread";
				}
			}
		}
		return "null"; // null
	}
	
	// start getMovieTitleId by splitting /
	//[http:, , m.imdb.com, title, tt0433035]

	public String getMovieTitleId(String myurl){
		//Log.i(LOG_TAG, " getMovieTitleId url -  "+myurl); 
		if(myurl!=""){	
			List<String> urlitems = Arrays.asList(myurl.split("/"));
			if(myurl.startsWith("http://m.imdb.com")&& urlitems.size()==5 
				&& urlitems.get(3).equals("title") && urlitems.get(4).toString()!="")
			{
				return urlitems.get(4).toString();
			}
			else if(myurl.startsWith("http://www.imdb.com")
					&& urlitems.get(3).equals("title") && urlitems.get(4).toString()!=""){
				return urlitems.get(4).toString();
			}
		}
		return "null";
	}
	
	
	// return js
	public String getJSfile(String location){
		if(location!=""){	
			if(location=="allthreads")
				return "allthreads.js";
			else if(location=="onethread")
				return "onethread.js";
			else{
				return "common.js";
			}
		}
		return "null"; // null
	}
	

	//open mb from button click
	private void openMboard(String myurl) {
		//Log.i(LOG_TAG, " myurl "+myurl); 
		if(myurl!=""){
			String movieId = getMovieTitleId(myurl);
			//Log.i(LOG_TAG, " movieId "+movieId); 

			if(movieId!="null"){
				String boardURL = "http://www.imdb.com/title/"+getMovieTitleId(myurl)+"/board/threads/";
				String myhtml = "";
				myhtml = extractHTML(boardURL,"allthreads.js");
				web1.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.872.0 Safari/535.2"); // user agent for desktop view
				web1.loadDataWithBaseURL(boardURL,myhtml, "text/html", "utf-8",boardURL);
			}
			
		}		
	}	
	
	//open mb from back button
		private void openMboardFromBack(String myurl) {
			//Log.i(LOG_TAG, " openMboardFromBack- "+myurl); 
			if(myurl!=""){
					String myhtml = "";
					String threadLocation = getThreadLocation(myurl);
					String loadJSfile = getJSfile(threadLocation); 
					myhtml = extractHTML(myurl,loadJSfile);
					web1.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.872.0 Safari/535.2"); // user agent for desktop view
					web1.loadDataWithBaseURL(myurl,myhtml, "text/html", "utf-8",myurl);
			}		
		}	
	

	// handle back key - get previous index from copyBackForwardList (current index -1)
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
	    if ((keyCode == KeyEvent.KEYCODE_BACK)&& backList.size()>0){
	    	
	    	Log.i(LOG_TAG, " ---------------------------------------------------- "); 
	    	
	    	for(int i=0;i<backList.size();i++)
	    	{
	    		Log.i(LOG_TAG, i + "-"+backList.get(i)); 
	    	}
	    	
	    	String lastItem = backList.get(backList.size()-1);
	    	backList.remove(lastItem);

	    	Log.i(LOG_TAG, " -------------------------REMOVE---------------------- "); 
	    	
	    	if(backList.size()>0){ //check array size again after remove
	    		for(int i=0;i<backList.size();i++)
		    	{
		    		Log.i(LOG_TAG, i + "-"+backList.get(i)); 
		    	}
		    	
		    	final String PrevUrl = backList.get(backList.size()-1);
		    	Log.i(LOG_TAG, " PrevUrl "+PrevUrl); 
		    	
		    	if(getImdbSite(PrevUrl).equals("mobile"))
		    	{
		    		web1.loadUrl(PrevUrl);
		    	}	
		    	else{
		    		//openMboard in new thread
			    	Thread t = new Thread(){
			    		   public void run(){
			    			  openMboardFromBack(PrevUrl);
			    		   }
			    	};
			    	t.start();
		    	}

	    	}
	    	
	    	
	    	
	    	
	    	Log.i(LOG_TAG, " ---------------------------------------------------- "); 
	    	
	    	
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
		
	
    //menu options
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		
		
		if(item.getTitle().equals("Clear Cache")){
			web1.clearCache(true);		
			Toast.makeText(this, "Cache Cleared", Toast.LENGTH_SHORT).show();
		}
		if(item.getTitle().equals("Message Board")){
			openMboard(CurrentWebviewURL);
		}
		if(item.getTitle().equals("Load in Browser")){
			Uri uri = Uri.parse(CurrentWebviewURL.toString());
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(browserIntent);
		}
		if(item.getTitle().equals("About")){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("IMDboards v1.0\n\u00A9 Murshid Muzamil 2011 \nIMDB logo and data are property of IMDB.com")
			       .setCancelable(true)
			       .setNeutralButton("Close", new DialogInterface.OnClickListener() {
										           public void onClick(DialogInterface dialog, int id) {
										        	   dialog.cancel(); 
										           }
			           
			       });

			AlertDialog alert = builder.create();
			alert.show();
		}
		if(item.getTitle().equals("Exit")){ // bring to homescreen
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_HOME);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		}
		
		if(item.getTitle().equals("Refresh")){ // bring to homescreen
			web1.reload();
		}
		
		return true;
	}
	
}